package com.cn.shuangzi.ad.custom;

import android.app.Activity;
import android.content.Context;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.mediation.MediationConstant;
import com.bytedance.sdk.openadsdk.mediation.bridge.custom.reward.MediationCustomRewardVideoLoader;
import com.bytedance.sdk.openadsdk.mediation.custom.MediationCustomServiceConfig;
import com.bytedance.sdk.openadsdk.mediation.custom.MediationRewardItem;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.bean.YlhErrorInfo;
import com.cn.shuangzi.ad.util.ADUtil;
import com.cn.shuangzi.ad.util.ThreadUtils;
import com.qq.e.ads.rewardvideo.RewardVideoAD;
import com.qq.e.ads.rewardvideo.RewardVideoADListener;
import com.qq.e.comm.constants.BiddingLossReason;
import com.qq.e.comm.util.AdError;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * YLH 激励视频广告自定义Adapter
 */
public class YlhCustomerReward extends MediationCustomRewardVideoLoader {

    private volatile RewardVideoAD mRewardVideoAD;
    private int price;

    @Override
    public void load(final Context context, final AdSlot adSlot, final MediationCustomServiceConfig serviceConfig) {

        /**
         * 在子线程中进行广告加载
         */
        ThreadUtils.runOnThreadPool(new Runnable() {
            @Override
            public void run() {
                RewardVideoADListener rewardVideoADListener = new RewardVideoADListener() {
                    @Override
                    public void onADLoad() {
                        ADUtil.logError("优量汇激励视频 onADLoad");
                        if (isClientBidding()) {//bidding类型广告
                            double ecpm = mRewardVideoAD.getECPM(); //当无权限调用该接口时，SDK会返回错误码-1
                            if (ecpm < 0) {
                                ecpm = 0;
                            }
                            price = (int) ecpm;
                            ADManager.getInstance().setRewardYlhErrorInfo(new YlhErrorInfo(BiddingLossReason.LOW_PRICE));
                            ADUtil.logError("优量汇激励视频ecpm:" + ecpm);
                            callLoadSuccess(ecpm);
                        } else {//普通类型广告
                            callLoadSuccess();
                        }
                    }

                    @Override
                    public void onVideoCached() {
                        ADUtil.logError("优量汇激励视频 onVideoCached");
                        callAdVideoCache();
                    }

                    @Override
                    public void onADShow() {
                        ADUtil.logError("优量汇激励视频 onADShow");
                        callRewardVideoAdShow();
                    }

                    @Override
                    public void onADExpose() {
                        ADUtil.logError("优量汇激励视频 onADExpose");
                    }

                    @Override
                    public void onReward(final Map<String, Object> map) {
                        float amount = 0f;
                        String name = "";
                        if (adSlot != null && adSlot.getMediationAdSlot() != null) {
                            amount = adSlot.getMediationAdSlot().getRewardAmount();
                            name = adSlot.getMediationAdSlot().getRewardName();
                        }
                        final float finalAmount = amount;
                        final String finalName = name;
                        ADUtil.logError("优量汇 激励视频 onReward name="+name+"，amount"+amount);
                        callRewardVideoRewardVerify(new MediationRewardItem() {
                            @Override
                            public boolean rewardVerify() {
                                return true;
                            }

                            @Override
                            public float getAmount() {
                                return finalAmount;
                            }

                            @Override
                            public String getRewardName() {
                                return finalName;
                            }

                            @Override
                            public Map<String, Object> getCustomData() {
                                return map;
                            }
                        });
                    }

                    @Override
                    public void onADClick() {
                        ADUtil.logError("优量汇激励视频 onADClick");
                        callRewardVideoAdClick();
                    }

                    @Override
                    public void onVideoComplete() {
                        ADUtil.logError("优量汇激励视频 onVideoComplete");
                        callRewardVideoComplete();
                    }

                    @Override
                    public void onADClose() {
                        ADUtil.logError("优量汇激励视频 onADClose");
                        callRewardVideoAdClosed();
                    }

                    @Override
                    public void onError(AdError adError) {
                        ADManager.getInstance().setRewardYlhErrorInfo(new YlhErrorInfo(BiddingLossReason.NO_AD));
                        if (adError != null) {
                            ADUtil.logError("优量汇激励视频 onNoAD errorCode = " + adError.getErrorCode() + " errorMessage = " + adError.getErrorMsg());
                            callLoadFail(adError.getErrorCode(), adError.getErrorMsg());
                        } else {
                            callLoadFail(40000, "no ad");
                        }
                    }
                };

                boolean isMuted = adSlot.getMediationAdSlot() == null ? false : adSlot.getMediationAdSlot().isMuted();
                if (isServerBidding()) {
                    mRewardVideoAD = new RewardVideoAD(context, serviceConfig.getADNNetworkSlotId(), rewardVideoADListener, !isMuted, getAdm());
                } else {
                    mRewardVideoAD = new RewardVideoAD(context, serviceConfig.getADNNetworkSlotId(), rewardVideoADListener, !isMuted);
                }

                ADManager.getInstance().setRewardYlhErrorInfo(new YlhErrorInfo(BiddingLossReason.OTHER));
                ADManager.getInstance().setRewardYlhAd(mRewardVideoAD);
                mRewardVideoAD.loadAD();
            }
        });
    }

    @Override
    public void showAd(final Activity activity) {
        ADUtil.logError("优量汇激励视频 showAd");
        if(mRewardVideoAD!=null&&price>0) {
            ADUtil.logError("上报优量汇 激励视频 竞价成功："+price);
            mRewardVideoAD.sendWinNotification(price);
        }
        /**
         * 先切子线程，再在子线程中切主线程进行广告展示
         */
        ThreadUtils.runOnUIThreadByThreadPool(new Runnable() {
            @Override
            public void run() {
                if (mRewardVideoAD != null) {
                    if (isServerBidding()) {
                        mRewardVideoAD.setBidECPM(mRewardVideoAD.getECPM());
                    }
                    mRewardVideoAD.showAD(activity);
                }
            }
        });

    }

    @Override
    public MediationConstant.AdIsReadyStatus isReadyCondition() {
        /**
         * 在子线程中进行广告是否可用的判断
         */
        Future<MediationConstant.AdIsReadyStatus> future = ThreadUtils.runOnThreadPool(new Callable<MediationConstant.AdIsReadyStatus>() {
            @Override
            public MediationConstant.AdIsReadyStatus call() throws Exception {
                if (mRewardVideoAD != null && mRewardVideoAD.isValid()) {
                    return MediationConstant.AdIsReadyStatus.AD_IS_READY;
                } else {
                    return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
                }
            }
        });
        try {
            MediationConstant.AdIsReadyStatus result = future.get(500, TimeUnit.MILLISECONDS);//设置500毫秒的总超时，避免线程阻塞
            if (result != null) {
                return result;
            } else {
                return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
    }

    @Override
    public void onPause() {
        super.onPause();
        ADUtil.logError("优量汇激励视频 onPause");
    }

    @Override
    public void onResume() {
        super.onResume();
        ADUtil.logError("优量汇激励视频 onResume");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ADUtil.logError("优量汇激励视频 onDestroy");
        mRewardVideoAD = null;
    }

    /**
     * 是否clientBidding广告
     *
     * @return
     */
    public boolean isClientBidding() {
        return getBiddingType() == MediationConstant.AD_TYPE_CLIENT_BIDING;
    }

    /**
     * 是否serverBidding广告
     *
     * @return
     */
    public boolean isServerBidding() {
        return getBiddingType() == MediationConstant.AD_TYPE_SERVER_BIDING;
    }

    @Override
    public void receiveBidResult(boolean win, double winnerPrice, int loseReason, Map<String, Object> extra) {
        super.receiveBidResult(win, winnerPrice, loseReason, extra);
    }
}
